/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Interfaces;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.List;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;
import lemar.ConexionHibernate;
import lemar.entidad.AreaProducto;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

/**
 *
 * @author Lkokain
 */
public class AgregarArea extends javax.swing.JPanel {

   private static SessionFactory sessionFactory = null;
   
    //Para limitar el numero de caracteres de un campo de texto
    private int limite  = 8;
    public AgregarArea() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        txtNombreArea = new javax.swing.JTextField();
        txtCodigoArea = new javax.swing.JTextField();
        btnCancelarArea = new javax.swing.JButton();
        btnAgregarArea = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        txtIdArea = new javax.swing.JTextField();
        cnbProductos = new javax.swing.JComboBox();

        setBackground(new java.awt.Color(255, 255, 255));
        setMaximumSize(new java.awt.Dimension(747, 435));
        setMinimumSize(new java.awt.Dimension(747, 435));
        setPreferredSize(new java.awt.Dimension(747, 435));

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("Agregar Area de Productos");

        jLabel2.setText("Nombre del area");

        jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel3.setText("Codigo del area");

        txtNombreArea.setToolTipText("Ingrese el nombre del área");
        txtNombreArea.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtNombreAreaActionPerformed(evt);
            }
        });
        txtNombreArea.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                txtNombreAreaFocusGained(evt);
            }
        });
        txtNombreArea.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtNombreAreaKeyTyped(evt);
            }
        });

        txtCodigoArea.setToolTipText("Ingrese el codigo del área");
        txtCodigoArea.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtCodigoAreaActionPerformed(evt);
            }
        });

        btnCancelarArea.setText("Cancelar");
        btnCancelarArea.setToolTipText("Anula la operacion");
        btnCancelarArea.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarAreaActionPerformed(evt);
            }
        });

        btnAgregarArea.setText("Ingresar");
        btnAgregarArea.setPreferredSize(new java.awt.Dimension(75, 23));
        btnAgregarArea.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAgregarAreaActionPerformed(evt);
            }
        });

        jLabel4.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel4.setText("Producto");

        jLabel5.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel5.setText("Identificacion");

        txtIdArea.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtIdAreaActionPerformed(evt);
            }
        });

        cnbProductos.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(224, 224, 224)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 299, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jLabel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(txtNombreArea, javax.swing.GroupLayout.DEFAULT_SIZE, 202, Short.MAX_VALUE)
                            .addComponent(txtIdArea)
                            .addComponent(txtCodigoArea)
                            .addComponent(cnbProductos, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                .addContainerGap(224, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(btnCancelarArea)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnAgregarArea, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(70, 70, 70)
                .addComponent(jLabel1)
                .addGap(60, 60, 60)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtNombreArea, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(txtCodigoArea, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(cnbProductos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(txtIdArea, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 115, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnAgregarArea, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnCancelarArea))
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void txtCodigoAreaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtCodigoAreaActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtCodigoAreaActionPerformed

    private void txtNombreAreaKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtNombreAreaKeyTyped
      char c;
c=evt.getKeyChar();
if(!(c<'0'||c>'9'))
evt.consume();
    }//GEN-LAST:event_txtNombreAreaKeyTyped

    private void btnAgregarAreaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAgregarAreaActionPerformed
     String codigo = "";
        String nombre = "";
        String productos = "";
        String identificacion = "";
        //Variable que maneja la respuesta del JOptionPane
        int conf;
        
        //Extrayendo la informacion de los campos de texto
        nombre = txtNombreArea.getText();
        codigo = txtCodigoArea.getText();
        productos =cnbProductos.getSelectedItem().toString();
        identificacion = txtIdArea.getText();
        if(!(nombre.isEmpty() || codigo.isEmpty() || productos.isEmpty())){ //Si no esta vacio algun campo           
        
            //Chunche de Hibernate (Inicio de sesion de hibernate)
            Session session = null;
            try{
                try{
                    //Conexion a la BD
                    sessionFactory = ConexionHibernate.getSessionFactory();
                    //Apertura de la sesion
                    session = sessionFactory.openSession();
                    Transaction tx = session.beginTransaction();

                    //Creando el objeto Proveedor 
                    AreaProducto area = new AreaProducto();
                    //Ingresando la informacion del proveedor al 
                    //objeto Proveedor
                    area.setNombre(nombre);
                   // area.setIdAreaProducto(codigo);
                    area.setProducto(productos);
                    area.setIdentificacion(identificacion);
                    //Mensaje de pregunta si quiere guardar los datos proporcionados 
                    conf=JOptionPane.showConfirmDialog(null,"¿Esta seguro de ingresar esos datos?","Confirmación",JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE);
                    
                    if(conf == JOptionPane.YES_OPTION){//Si la opcion fue SI
                        //Guardando el objeto en la base de datos
                        session.save(area);
                        tx.commit();
                        txtCodigoArea.setText("");
                        txtNombreArea.setText("");
                        
                        txtIdArea.setText("");
                        //Mensaje de confirmacion de insercion Exitosa
                        JOptionPane.showMessageDialog(null,"Registro guardado exitosamente","Información",JOptionPane.INFORMATION_MESSAGE);                        
                    }     
                }catch(Exception e){
                    System.out.println(e.getMessage());
                }
            } finally {
                //Finalizacion de la sesion de hibernate
                session.close();
        }
      }
        else {//Si hay campos vacios, mensaje de error
            JOptionPane.showMessageDialog(null,"Error, no pueden haber campos vacios","Error en los datos",JOptionPane.ERROR_MESSAGE);
        }
        
    }//GEN-LAST:event_btnAgregarAreaActionPerformed

    private void btnCancelarAreaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarAreaActionPerformed
        txtCodigoArea.setText("");
        txtNombreArea.setText("");
//        txtProductoArea.setText("");
        txtIdArea.setText("");
    }//GEN-LAST:event_btnCancelarAreaActionPerformed

    private void txtIdAreaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtIdAreaActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtIdAreaActionPerformed

    private void txtNombreAreaFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtNombreAreaFocusGained
        // TODO add your handling code here:
    }//GEN-LAST:event_txtNombreAreaFocusGained

    private void txtNombreAreaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtNombreAreaActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtNombreAreaActionPerformed

   private void cargarComboBox(){
    List<AreaProducto> listaArea = null;
        
        //Inicializacion de session de hibernate
        Session session = null;
        try{
            try{
                //Chunces que ocupa Hibernate
                sessionFactory = ConexionHibernate.getSessionFactory();
                session = sessionFactory.openSession();
                Transaction tx = session.beginTransaction();
                
                //Obteniendo de la BD todos los proveedores                
                listaArea = session.createQuery("from AreaProducto").list();
                
                //Creando un modelo de comboBox                
                DefaultComboBoxModel modeloCombo = new DefaultComboBoxModel();
                
                //Poniendole un mensaje de seleccion (Pirmer elemento)
                 modeloCombo.addElement("<--Seleccione un producto-->");
                
                //Llenando el modelo de comboBox con los nombres de los proveedores
                for(AreaProducto p : listaArea) 
                { 
                    modeloCombo.addElement(p.getProductos());                     
                }
                
                //Agregando el modelo del comboBox al comboBox del panel
                cnbProductos.setModel(modeloCombo);
                
            }catch(Exception e){
                    System.out.println(e.getMessage());
                }
            }finally {
                session.close();
        }
        
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAgregarArea;
    private javax.swing.JButton btnCancelarArea;
    private javax.swing.JComboBox cnbProductos;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JTextField txtCodigoArea;
    private javax.swing.JTextField txtIdArea;
    private javax.swing.JTextField txtNombreArea;
    // End of variables declaration//GEN-END:variables
}
